﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace Space_Conquest
{
    class MapLoader : Map
    {

        public MapLoader(GameEngine parent, string mapName)
        {

            LoadMap(parent, mapName);

        }

        public MapLoader(GameEngine parent, string mapName, string mapHash)
        {

            // Check hash
            if (mapHash != MD5.HashFile(Globals.RESOURCE_DIRECTORY + @"Maps\" + mapName + ".map"))
                throw new Exception("Error, the server has a different map version than you. Cannot join game.");

            LoadMap(parent, mapName);

        }

        void LoadMap(GameEngine parent, string mapName)
        {

            using (StreamReader sr = new StreamReader(Globals.RESOURCE_DIRECTORY + @"Maps\" + mapName + ".map"))
            {

                List<List<int>> firstArray = new List<List<int>>();

                while (!sr.EndOfStream)
                {

                    List<int> tempList = new List<int>();
                    string line = sr.ReadLine();

                    foreach (string s in line.Split('|'))
                        tempList.Add(Convert.ToInt32(s));

                    firstArray.Add(tempList);

                }

                int[,] secondArray = new int[firstArray.Count, firstArray[0].Count];

                for (int j = 0; j < firstArray[0].Count; ++j)
                {
                    for (int i = 0; i < firstArray.Count; ++i)
                    {
                        secondArray[i, j] = firstArray[i][j];
                    }
                }

                InitMapWithArray(parent, secondArray);

            }

        }

    }
    
}
